package com.authine.cloudpivot.ext.controller.workList;


import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/public/NameRecordController")
public class NameRecordController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    /**
     * 命名记录  审批流完成后 数据写到-命名记录基础表
     */
    @Async
    @RequestMapping("finish")
    public void finish(@RequestParam String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.NamedRecord, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.NamedRecordDetail);
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, "Activity28");
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                // 判断是否是修改
                String id = existsBizObject(map);
                if (StringUtils.isNotBlank(id)) {
                    data.put("id", id);
                }

//                String basicId = MapUtils.getString(map, "basicId", "");
//                if (StringUtils.isNotBlank(basicId)) {
//                    //基础信息表id
//                    data.put("id", basicId);
//                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.NamedRecordBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("命名基础表更新数据,id:{}", id);
                finishOrModifiyProcess(id);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * ----命名记录
     * exec   SyncNameRecord
     *
     * @name nvarchar(100),                    ----名称
     * @simple nvarchar(50),                    ----简称
     * @foreign nvarchar(50),                    ----外文名称
     * @shortname nvarchar(100),            ----缩写
     * @funcode nvarchar(100),                ----职能代码
     * @maindeptid nvarchar(100),            ----主责部门FID
     * @EAS nvarchar(100),                    ----EAS
     * @archtypeID nvarchar(100),                ----档案类型FID
     * @Code nvarchar(100),                ----相关档案代码
     * @Auditor nvarchar(100)                ----审批人		02.0100 张三
     */
    private void finishOrModifiyProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.NamedRecordBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        String designation = MapUtils.getString(map, "designation", "");  // 名称
        String abbreviation = MapUtils.getString(map, "abbreviation", ""); //简称
        String english_name = MapUtils.getString(map, "english_name", "");// 英文名称
        String english_nameReplace = english_name.replace("'", "''");
        String abbreviations = MapUtils.getString(map, "abbreviations", ""); // 缩写
        String functionFNumber = MapUtils.getString(map, "functionFNumber", ""); // 职能代码
        String responsibleDeptFid = MapUtils.getString(map, "responsibleDeptFid", ""); // 主责部门代码关联
        String esa = MapUtils.getString(map, "esa", ""); //esa
        String relatedFileType = MapUtils.getString(map, "relatedFileType", ""); //档案类型FID
        String relatedFileCode = MapUtils.getString(map, "relatedFileCode", "");// 相关档案代码
        String approval = MapUtils.getString(map, "approval", ""); // 审批人

        //暂不校验
//        Assert.isFalse(StringUtils.isEmpty(designation), "{}不能为空", "designation");
//        Assert.isFalse(StringUtils.isEmpty(abbreviation), "{}不能为空", "abbreviation");
//        Assert.isFalse(StringUtils.isEmpty(english_name), "{}不能为空", "english_name");
//        Assert.isFalse(StringUtils.isEmpty(abbreviations), "{}不能为空", "abbreviations");
//        Assert.isFalse(StringUtils.isEmpty(functionFNumber), "{}不能为空", "functionFNumber");
//        Assert.isFalse(StringUtils.isEmpty(responsibleDeptFid), "{}不能为空", "responsibleDeptFid");
//        Assert.isFalse(StringUtils.isEmpty(esa), "{}不能为空", "esa");
//        Assert.isFalse(StringUtils.isEmpty(relatedFileType), "{}不能为空", "relatedFileType");
//        Assert.isFalse(StringUtils.isEmpty(relatedFileCode), "{}不能为空", "relatedFileCode");
//        Assert.isFalse(StringUtils.isEmpty(approval), "{}不能为空", "approval");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncNameRecord '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                designation, abbreviation, english_nameReplace, abbreviations, functionFNumber,
                responsibleDeptFid, esa, relatedFileType, relatedFileCode, approval);
        log.info("\n==========准备调用[命名记录]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[命名记录]存储过程执行完成");
    }

    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

//        //事项基础表id映射
        String designation = (String) data.get("designation");

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.NamedRecordBasic);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName).append(" as A where A.designation ='").append(designation).append("' ORDER BY createdTime desc limit 1");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 命名记录基础表修改 -- 废弃
     */
    @Async
    @RequestMapping("modify")
    public void modify(String bizId) {

        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.NamedRecordModify, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.NamedRecordDetailModify);
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, "Activity28");
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.NamedRecordBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                String id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                // 存储过程
                finishOrModifiyProcess(id);
            } catch (Exception e) {
                log.info("参数：{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.NamedRecordCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.NamedRecordDetailCancel);
        //获取审批人
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, "Activity28");
        for (Map<String, Object> map : list) {
            try {
                String bascid = (String) map.get("eventObjectId");
                //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
                if (StringUtils.isBlank(bascid)) {
                    continue;
                }
                //获取数据
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                data.put("id", bascid);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.NamedRecordBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                toVoidProcess(MapUtils.getString(map, "designation", ""));
            } catch (Exception e) {
                log.info("参数：{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

//    @RequestMapping("toVoidProcess1")
//    public void toVoidProcess1(String designation) {
//        String execSql = String.format("exec [HG_LINK].[hg].[dbo].NameRecordVoid '%s'",
//                designation);
//        log.info("\n==========准备调用[命名记录]存储过程:{}", execSql);
//        sqlService.execute(CloudSqlService.htEas, execSql);
//        log.info("\n=============[命名记录]存储过程执行完成");
//    }

    /**
     * 命名记录作废存储过程
     *
     * @param designation
     */
    private void toVoidProcess(String designation) {
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].NameRecordVoid '%s'",
                designation);
        log.info("\n==========准备调用[命名记录]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[命名记录]存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String finalActivityCode) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


}
